package com.ksd.pug.clound.controller;

import com.ksd.pug.clound.pojo.SysUser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/2/25 15:47
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallback",
        commandProperties = {
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "SEMAPHORE"),//信号量隔离
            // 读取数据超时实际默认是：1000ms
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "3000"),
            // 该属性用来设置从调用线程中允许HystrixCommand.getFallback()方法执行的最大并发请求数。当达到最大并发请求时，后续的请求将会被拒绝并抛出异常。
            // 限制并发数，A--B 如果请求数REQUESTS超过你设定的FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS=5000,直接抛出异常
            // 这个的值设置多少呢？FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS 不要超过tomcat最大等待线程数连接数 8192，
            @HystrixProperty(name = HystrixPropertiesManager.FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "5000"),
            // 信号量最大并发数 通行证的个数 EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "5000")
        }
    )
    @GetMapping("/user/{id}")
    public SysUser findUsers(@PathVariable("id") Long id) {
        log.info("===========findusers================");
        return restTemplate.postForObject("http://kuangstudy-hystrix-user-service/api/user/" + id, null, SysUser.class);
    }

    public SysUser fallback(Long id) {
        SysUser sysUser = new SysUser();
        sysUser.setId(-1L);
        return sysUser;
    }

}
